package com.demo.web;

import com.demo.config.Test;
import com.demo.domain.entity.Config;
import com.demo.domain.entity.Language;
import com.demo.domain.entity.User;
import com.demo.service.TestService;
import com.demo.thread.Runner;
import org.apache.commons.lang3.StringEscapeUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.Errors;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletRequestWrapper;
import javax.servlet.http.HttpSession;
import javax.validation.Valid;
import java.util.*;
import java.util.concurrent.*;

/**
 * Created by miaorf on 2016/8/2.
 */
@RequestMapping("/hello")
@Controller
public class HelloController {

    @Autowired
    Config config;

    @Autowired
    Language language;

    @RequestMapping("/index")
    public String hello(Model model, @RequestParam(defaultValue = "Ryan") String name){
        model.addAttribute("name",name);
        return "index";
    }

    @ResponseBody
    @RequestMapping("/info")
    public Map info(@Valid @ModelAttribute("user")User user, Errors errors){

        Map map = new HashMap();
        if (errors.hasErrors()){
            map.put("error",errors.getAllErrors());
        }else{
            map.put("user",user);
        }

        map.put("config", config);
        map.put("language", language);
        return map;
    }

    @RequestMapping("/user")
    public String user(@Valid @ModelAttribute("user")User user, Errors errors, Model model, String xss,
                       @RequestParam(defaultValue = "true") boolean injection){
        if (injection) {
            xss = StringEscapeUtils.escapeHtml4(xss);
        }
        model.addAttribute("xss", xss);
        if (errors.hasErrors()){
            model.addAttribute("error",errors.getAllErrors());
        }else{
//            model.addAttribute("user",user);
        }

        return "user";
    }



    @RequestMapping(value = "/map.json", method = {RequestMethod.GET,RequestMethod.POST})
    @ResponseBody
    public Map map(){
        Map map = new HashMap();
        map.put("name","Ryan");
        map.put("sex","man");
        map.put("age",18);
        List list = new ArrayList();
        list.add("red");
        list.add("black");
        list.add("blue");
        list.add("yellow");
        map.put("colors",list);
        return map;
    }
    @ResponseBody
    @RequestMapping("/test")
    public String test(Integer str)throws Exception{
        if(str==1){
            Thread.sleep(10000);
        }
        return str.toString();
    }
    @ResponseBody
    @RequestMapping("/testThread")
    public String testThread(Integer str){
        if(str==1){
            try {
                Thread.sleep(10000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
        List<Future<String>> futures = new ArrayList<>();
        CyclicBarrier barrier = new CyclicBarrier(3);
        ExecutorService executorService = Executors.newFixedThreadPool(3);
        futures.add(executorService.submit(new Runner(barrier,"1号") ));
        futures.add(executorService.submit(new Runner(barrier,"2号") ));
        futures.add(executorService.submit(new Runner(barrier,"3号") ));
        executorService.shutdown();
        for(Future future : futures){
            try {
                System.out.println(future.get());
            } catch (InterruptedException e) {
                e.printStackTrace();
            } catch (ExecutionException e) {
                e.printStackTrace();
            }
        }
        return str.toString();
    }
    public static void test() throws InterruptedException {
        List<Future<String>> futures = new ArrayList<>();
        CyclicBarrier barrier = new CyclicBarrier(3);
        ExecutorService executorService = Executors.newFixedThreadPool(3);
        ExecutorService executorService1 = new ThreadPoolExecutor(3, 3,
                0L, TimeUnit.MILLISECONDS,
                new LinkedBlockingQueue<Runnable>());
        futures.add(executorService1.submit(new Runner(barrier,"1号")));
        futures.add(executorService1.submit(new Runner(barrier,"2号")));
        futures.add(executorService1.submit(new Runner(barrier,"3号")));
        executorService.shutdown();
        for(Future future : futures){
            try {
                System.out.println(future.get());
            } catch (InterruptedException e) {
                e.printStackTrace();
            } catch (ExecutionException e) {
                e.printStackTrace();
            }
        }
        System.out.println("wancheng");

    }
    public static void main(String[] args) throws InterruptedException {
    }
    private static void printException(Runnable r, Throwable t) {
        if (t == null && r instanceof Future<?>) {
            try {
                Future<?> future = (Future<?>) r;
                if (future.isDone())
                    future.get();
            } catch (CancellationException ce) {
                t = ce;
            } catch (ExecutionException ee) {
                t = ee.getCause();
            } catch (InterruptedException ie) {
                Thread.currentThread().interrupt(); // ignore/reset
            }
        }
        if (t != null)
           System.err.println(t.getMessage());
    }

    @Autowired
    private TestService testService;
    @Test
    @RequestMapping("/test1")
    @ResponseBody
    public void testAop(){
        testService.testCheck();
    }
}
